<template>
  <view>
    <u-navbar :bgColor="navbarBgColor">
      <view slot="left" class="backIcon">
        <u-icon
          name="arrow-left"
          @click="back"
          size="20px"
          color="#333"
        ></u-icon>
      </view>
      <view slot="center">
        <u-tabs
          :current="currentTab"
          @change="changeTab"
          :list="[{ name: '商品信息' }, { name: '评价' }, { name: '详情' }]"
          line-color="#72b093"
        ></u-tabs>
      </view>
    </u-navbar>
    <scroll-view
      scroll-y
      :style="{ height: `calc(100vh - ${pageFooterHeight}px)` }"
      :scroll-into-view="scrollInTo"
      @scroll="pageScroll"
      :scroll-with-animation="true"
    >
      <view id="swiper">
        <u-swiper
          height="750rpx"
          :list="swiperList"
          keyName="url"
          :autoplay="false"
        ></u-swiper>
      </view>
      <view class="px-12 flex-col gap-12 py-12">
        <view id="goodsDetail">
          <view class="active-coupon color-white p-10 border-box">
            <view class="flex justify-between">
              <view class="flex">
                <view>
                  <text class="text-14">￥</text>
                  <text class="text-18">{{ goodsData.price }}</text>
                </view>
                <!--                <view class="activity-nav"> 活动最低到手￥29.9 &gt;</view>-->
              </view>
              <!--              <view class="text-18">新人券活动</view>-->
            </view>
            <view class="flex justify-end items-center text-12 pt-12 pb-8">
              <!-- <text> 最高返39积分 </text> -->
              <text>剩余{{ goodsData.stockTotal }}件</text>
            </view>
          </view>
          <!--    上方活动区域不存在 top--12设置为false    -->
          <view class="shadow-card p-12" :class="{ 'top--12': true }">
            <!-- 优惠券 -->
            <!-- <Coupon></Coupon>
						<view class="flex items-center justify-between pt-12">
							<view class="flex gap-8">
								<view class="flex tag-error">
									<view class="border-right-dashed pr-4">券</view>
									<view>12盒减10元</view>
								</view>
								<view class="flex tag-error">
									<view class="border-right-dashed pr-4">券</view>
									<view>12盒减10元</view>
								</view>
							</view>
							<view>
								<u-button color="red" text="领劵" size="mini" shape="circle"></u-button>
							</view>
						</view> -->

            <view class="text-14 color-black text-bold pt-12">
              {{ goodsData.goodsName }}
            </view>
            <view class="flex justify-between text-10 pt-10">
              <view class="color-warning">{{
                goodsData.description || ""
              }}</view>
              <!-- <view class="color-gray">销量 1234</view> -->
            </view>
          </view>

          <view class="mt-12 flex-col gap-16 shadow-card p-12">
            <view class="flex" @click="selectSku">
              <view class="color-gray text-12 w-64">规格</view>
              <view class="flex-1 flex justify-between text-12">
                <view>有{{ goodsData.styleCount }}种规格可选</view>
                <u-icon name="arrow-right" size="24rpx" color="#999"></u-icon>
              </view>
            </view>
            <view class="flex">
              <view class="color-gray text-12 w-64">配送</view>
              <view
                class="flex-1 flex justify-between text-12"
                @click="selectShopAddress"
              >
                <view class="flex items-center">
                  <u-icon name="map-fill" size="24rpx" color="#1f1f1f"></u-icon>
                  <view class="ml-4 u-line-1">
                    {{ address.detailAddress || "请选择收货地址" }}
                  </view>
                </view>
                <u-icon name="arrow-right" size="24rpx" color="#999"></u-icon>
              </view>
            </view>
            <view class="flex">
              <view class="color-gray text-12 w-64">购物保障</view>
              <view class="flex-1 flex justify-between text-12">
                <view
                  ><text class="color-primary mr-4">安心购</text>
                  7天无理由退换货</view
                >
              </view>
            </view>
            <!-- <view class="flex">
							<view class="color-gray text-12 w-64">证照</view>
							<view class="flex-1 flex justify-between text-12">
								<view class="flex items-center">
									<u-icon name="photo-fill" size="24rpx" color="#6ac09c"></u-icon>
									<text>经营资质</text>
								</view>
							</view>
						</view> -->
          </view>
          <!--店铺-->
          <view
            class="shadow-card p-12 flex mt-12 items-center justify-between"
          >
            <view class="flex">
              <u-image
                radius="12rpx"
                :src="merchant.logoUrl"
                width="100rpx"
                height="100rpx"
              ></u-image>
              <view class="pl-10">
                <view class="text-12 text-bold u-line-1">
                  {{ merchant.merchantName }}
                </view>
                <view class="flex gap-8 pt-10">
                  <view class="tag-error ellipsis-1">销量1234万</view>
                  <view class="tag-error ellipsis-1">回头客1234万+</view>
                </view>
                <view class="pt-10 flex text-10 color-gray">
                  <u-rate
                    :count="5"
                    :value="4.8"
                    size="28rpx"
                    gutter="4rpx"
                    allowHalf
                  ></u-rate>
                  <text class="text-red ml-4">4.8</text>
                  <text class="ml-4">| 1234关注</text>
                  <text class="ml-4">| 1234件商品</text>
                </view>
              </view>
            </view>
            <view>
              <u-button
                type="primary"
                plain
                text="进店"
                shape="circle"
                :custom-style="{ height: '32px' }"
                @click="navToStoreCenter"
              ></u-button>
            </view>
          </view>
        </view>

        <!--        <view id="comment">-->
        <!--          &lt;!&ndash;   购买记录&ndash;&gt;-->
        <!--          &lt;!&ndash; <view class="shadow-card p-12">-->
        <!--						<view class="flex justify-between" @click="handelPurchaseRecord">-->
        <!--							<view class="text-16 text-bold">购买记录</view>-->
        <!--							<u-icon label-pos="left" name="arrow-right" label-color="#999" label-size="24rpx"-->
        <!--								label="查看更多" size="24rpx" color="#999"></u-icon>-->
        <!--						</view>-->
        <!--						<view class="h-70 over-hidden mt-12">-->
        <!--							<AutoScroll>-->
        <!--								<view class="flex-col gap-10 pb-10">-->
        <!--									<BuyRecord v-for="i in 10" :key="i"></BuyRecord>-->
        <!--								</view>-->
        <!--							</AutoScroll>-->
        <!--						</view>-->
        <!--					</view> &ndash;&gt;-->

        <!--          &lt;!&ndash; <view class="mt-12 shadow-card p-12" @click="goGoodsComment">-->
        <!--						<view class="flex justify-between">-->
        <!--							<view class="text-bold text-16">用户评价(12.3万+)</view>-->
        <!--							<view class="color-gray text-12">满意度12.3%</view>-->
        <!--						</view>-->
        <!--						<GoodDegreeSurprise readonly></GoodDegreeSurprise>-->
        <!--						<view class="mt-12">-->
        <!--							<EvaluateItem></EvaluateItem>-->
        <!--							<view class="flex justify-center pt-12">-->
        <!--								<u-icon label-pos="left" name="arrow-right" label-color="#999" label-size="24rpx"-->
        <!--									label="查看全部评价" size="24rpx" color="#999"></u-icon>-->
        <!--							</view>-->
        <!--						</view>-->
        <!--					</view> &ndash;&gt;-->
        <!--        </view>-->
        <view id="detail" class="shadow-card p-12">
          <u-parse
            v-if="content && content !== '<p></p>'"
            :content="content"
          ></u-parse>
          <u-empty
            v-else
            mode="data"
            marginTop="20px"
            text="暂无详情"
          ></u-empty>
        </view>
      </view>
    </scroll-view>

    <view
      class="fix-right flex-col gap-12 pb-12"
      :style="{ bottom: pageFooterHeight + 'px' }"
    >
      <view class="fix-item" @click="navToCart">
        <u-badge
          max="99"
          :value="cardnumber"
          absolute
          :offset="[2, 1]"
        ></u-badge>
        <u-icon name="shopping-cart" size="50rpx" color="#333"></u-icon>
      </view>
      <view class="fix-item">
        <button open-type="share" class="u-reset-button">
          <u-icon name="share" size="50rpx" color="#333"></u-icon>
        </button>
      </view>
      <view class="fix-item" v-if="navbarBgColor !== 'transparent'">
        <u-icon
          name="arrow-up"
          size="50rpx"
          color="#333"
          @click="scrollToTop"
        ></u-icon>
      </view>
    </view>

    <!--  底部  -->
    <u-gap :height="pageFooterHeight"></u-gap>
    <view class="page-footer u-border-top py-6">
      <view class="flex w-375 border-box items-center gap-12 px-12">
        <u-icon
          name="home"
          label="首页"
          label-pos="bottom"
          size="40rpx"
          label-size="12px"
          label-color="#333"
          @click="goHome"
        ></u-icon>
        <u-button
          text="加入购物车"
          type="error"
          plain
          shape="circle"
          @click="selectSku('cart')"
        ></u-button>
        <u-button
          color="linear-gradient(to right, #e56133, #e04026)"
          shape="circle"
          @click="selectSku('buy')"
          text="立即购买"
        >
          <!--          <view class="text-center h-40 line-height-16 text-14">-->
          <!--            <view class="line-height-21">领劵购买</view>-->
          <!--            <view>劵后￥99元起</view>-->
          <!--          </view>-->
        </u-button>
      </view>
      <u-safe-bottom></u-safe-bottom>
    </view>
    <!-- <u-popup :show="purchaseRecordShow" round="24" mode="bottom" closeable @close="closePurchaseRecord">
			<view class="text-16 h-40 text-bold flex items-center justify-center">
				<text>购买记录</text>
			</view>
			<view class="p-12">
				<scroll-view scroll-y style="height: 60vh">
					<view class="flex-col gap-10">
						<BuyRecord v-for="i in 10" :key="i"></BuyRecord>
					</view>
				</scroll-view>
			</view>
		</u-popup> -->
    <geek-sku
      v-model="skuShow"
      :data="skus"
      :themeColor="[97, 184, 138]"
      :defaultCover="goodsData.coverImage"
      isMaskClose
      :btnConfirmText="skuType === 'buy' ? '立即购买' : '加入购物车'"
      notSelectSku="请选择完整的商品信息"
      @skuChange="skuChange"
      @confirm="skuConfirm"
    ></geek-sku>

    <ShippingAddressPop
      ref="addreddPopRef"
      :show.sync="shippingAddressShow"
      @setAddress="setAddress"
    >
    </ShippingAddressPop>

    <LoginModel :show.sync="showLogin" @afterLogin="afterLogin"></LoginModel>
  </view>
</template>

<script>
import LoginModel from "../../pages/my/loginModel.vue";
import Coupon from "@/subpages/components/coupon/index.vue";
import AutoScroll from "@/subpages/components/autoScroll/index.vue";
import BuyRecord from "@/subpages/components/buyRecord/index.vue";
import EvaluateItem from "@/subpages/components/evaluateItem/index.vue";
import GoodDegreeSurprise from "@/subpages/components/goodDegreeSurprise/index.vue";
import ShippingAddressPop from "@/subpages/components/shippingAddressPop/index.vue";
import store from "@/store/index.js";
import { mapMutations, mapActions } from "vuex";
import {
  fetchDeliveryAddressList,
  fetchGoodsDetail,
  fetchOrderCreate,
  fetchShoppingCartAdd,
  fetchShoppingCartList,
} from "@/services/api";
import { isEmpty } from "@/utils";
export default {
  components: {
    LoginModel,
    Coupon,
    AutoScroll,
    BuyRecord,
    EvaluateItem,
    GoodDegreeSurprise,
    ShippingAddressPop,
  },
  data() {
    return {
      swiperList: [],
      pageFooterHeight: 50,
      navbarBgColor: "transparent",
      scrollInTo: "",
      scrollInToHeightList: [],
      currentTab: 0,
      navHeight: 44,
      //控制收货地址弹出
      shippingAddressShow: false,
      //控制购买记录弹出
      purchaseRecordShow: false,
      showTip: false,
      //控制商品规格组件
      skuShow: false,
      //商品规格类型 'buy' 购买
      skuType: null,
      goodsData: {
        goodsImageList: [],
      },

      skus: [],
      content: "",
      // content: `
      // 	<p>露从今夜白，月是故乡明</p>
      // 	<img src="https://cdn.uviewui.com/uview/swiper/2.jpg" />
      // `,
      address: {},
      // 商户信息
      merchant: {},
      goodsgid: null,
      cardnumber: 0,
      goodsNo: "",
      showLogin: false,
    };
  },
  methods: {
    ...mapMutations("user", {
      afterLogin: "afterLogin",
      setIdentityList: "setIdentityList",
      setCurrentIdentity: "setCurrentIdentity",
    }),
    ...mapActions("goods", ["updateShoppingCartNum"]),
    navToCart() {
      this.$Router.push({
        name: "shopCar",
      });
    },
    getFooterHeight() {
      this.$uGetRect(".page-footer").then(({ height = 50 }) => {
        this.pageFooterHeight = height;
      });
    },
    async getRect() {
      try {
        const res = await Promise.all(
          ["goodsDetail", "comment", "detail"].map((item) =>
            this.$uGetRect(`#${item}`),
          ),
        );
        console.log("成功结果", res); // 处理成功的结果
        this.scrollInToHeightList = res.map((item) => item.top);
      } catch (error) {
        console.error("Error fetching rectangles:", error); // 处理错误
      }
    },
    back() {
      // uni.navigateBack();
      this.$Router.back();
    },
    pageScroll(e) {
      const { scrollTop } = e.detail;
      if (scrollTop > 390 && this.navbarBgColor === "transparent") {
        this.navbarBgColor = "#f5f6f7";
        this.navbarTitleStyle = "color:black";
      }
      if (scrollTop < 390) {
        this.navbarBgColor = "transparent";
        this.navbarTitleStyle = "color:white";
      }
      //处理滚动后的tab切换
      uni.$u.debounce(() =>
        this.scrollSetCurrentTab(scrollTop + this.navHeight, 100),
      );
    },
    goHome() {
      this.$Router.pushTab({
        name: "index",
      });
    },
    //处理滚动后的tab切换
    scrollSetCurrentTab(scrollTop) {
      let currentIndex = 0;
      this.scrollInToHeightList.forEach((item, index) => {
        if (scrollTop >= item) {
          currentIndex = index;
        }
      });

      this.currentTab = currentIndex;
      this.scrollInTo = "";
    },
    changeTab({ index }) {
      const ids = ["goodsDetail", "comment", "detail"];
      this.scrollInTo = ids[index];
      this.currentTab = index;
    },
    scrollToTop() {
      this.scrollInTo = "swiper";
    },
    //点击购买记录
    handelPurchaseRecord() {
      this.purchaseRecordShow = true;
    },
    // 关闭购买记录
    closePurchaseRecord() {
      this.purchaseRecordShow = false;
    },
    /**
     * 选择规格
     * @param type - 'buy' 购买 'cart' 加入购物车
     */
    async selectSku(type) {
      this.skuType = type;
      //该商品没有规格则直接购买或者加入购物车
      if (isEmpty(this.skus)) {
        type === "buy"
          ? await this.goBuy()
          : await this.addToCart({
              goodsNo: this.goodsNo,
              quantity: "1",
              coverImage: this.goodsData.coverImage,
              goodsSkuInfo: JSON.stringify({
                skuText: "无规格",
                num: this.goodsData.quantity,
              }),
            });
        return;
      }
      this.skuShow = true;
    },
    skuChange(sku) {
      console.log(sku);
    },
    //sku确认事件
    async skuConfirm(sku) {
      if (this.skuType === "buy") {
        await this.goBuy(sku);
      } else {
        await this.addToCart({
          goodsNo: this.goodsNo,
          goodsSkuNo: sku?.sku?.id,
          goodsSkuInfo: JSON.stringify(sku),
          quantity: sku?.num || "1",
        });
      }
    },
    /**
     * 商品加入购物车
     * @param data - 商品信息请求参数
     */
    async addToCart(data) {
      const { error } = await fetchShoppingCartAdd({
        ...data,
      });
      if (!error) {
        uni.$u.toast("已加入购物车");
        this.skuShow = false;
        this.getGoodsCart();
      }
    },
    /**
     * 立即购买商品
     */
    async goBuy(sku) {
      if (!this.address?.serialNo) {
        this.shippingAddressShow = true;
        uni.$u.toast("请选择收货地址");
        return;
      }
      const { data, error } = await fetchOrderCreate({
        type: "2",
        source: "wxapp",
        deliveryAddressNo: this.address?.serialNo,
        remark: "单品下单",
        goodsList: [
          {
            merchantNo: this.goodsData.merchantNo,
            goodsNo: this.goodsNo,
            goodsSkuNo: sku?.sku?.id,
            quantity: (sku?.num || 1) + "",
          },
        ],
      });
      if (!error) {
        this.$Router.push({
          name: "orderConfirm",
          params: {
            serialNo: data.serialNo,
          },
        });
      }
    },

    goGoodsComment() {
      this.$Router.push({
        name: "goodsComment",
        params: {
          id: 1,
        },
      });
    },
    setAddress(val) {
      console.log(val);
      this.address = val;
    },
    selectShopAddress() {
      this.shippingAddressShow = true;
    },
    navToStoreCenter() {
      let ths = this;
      this.$Router.push({
        name: "businessCenter",
        params: {
          data: JSON.stringify(this.merchant),
        },
      });
    },
    async getGoodsDetail(serialNo) {
      this.goodsNo = serialNo;
      const { data, error } = await fetchGoodsDetail({
        serialNo,
      });
      if (!error) {
        this.content = data.content || "";
        this.goodsData = data;
        this.swiperList = data.goodsImageList.map((item) => {
          return {
            url: item.imageUrl || item.multimediaUrl,
            ...item,
          };
        });
        this.skus = data.skuList.map((item) => {
          return {
            goodsNo: item.goodsNo,
            id: item.goodsSkuNo,
            sku_attrs: item.skuSpecJson,
            stock: item.stockNum,
            price: item.price,
          };
        });
        // 获取款式详情
        let styleCount = new Set();
        data.skuList.forEach((item) => {
          console.log("数据是", item.skuSpecJson["颜色"]);
          if (item.skuSpecJson) {
            styleCount.add(item.skuSpecJson["颜色"]);
          }
        });
        this.goodsData.styleCount = styleCount.size;
        // 获取商户信息
        this.merchant = {
          ...this.goodsData.merchant,
          merchantNo: data.merchantNo,
        };
        this.goodsgid = data.attributeList.map((item) => {
          return item.goodsNo;
        });
      }
    },
    //获取购物车
    async getGoodsCart() {
      const { code, data } = await fetchShoppingCartList();
      console.log(code);
      console.log(data);
      console.log(data.length);
      if (code == 0) {
        this.cardnumber = data.length;
        this.updateShoppingCartNum(data.length);
      }
    },
    //获取默认地址
    async getAddressList() {
      const { data, error } = await fetchDeliveryAddressList();
      if (!error) {
        const defaultAddress = data.find((item) => item.defaultAddress);
        if (defaultAddress) {
          this.setAddress(defaultAddress);
        }
      }
    },
  },
  onLoad(options) {
    console.log(options);

    if (store.state.user.token == null) {
      this.showLogin = true;
    }

    this.getFooterHeight();
    // 在元素加载完成后，再获取节点信息
    this.getRect();
    this.navHeight = 44 + uni.$u.sys().statusBarHeight;
    if (options.serialNo == null) {
      this.getGoodsDetail(this.$route.params.serialNo);
    } else {
      this.getGoodsDetail(options.serialNo);
    }
    this.getAddressList();
    this.getGoodsCart();
  },
  mounted() {
    this.getGoodsCart();
  },
};
</script>
<style>
page {
  background-color: #f6f7f9;
}
</style>
<style lang="scss" scoped>
.backIcon {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  // border: 0.5px solid #e5e5e5;
}

.fix-right {
  position: fixed;
  bottom: 0;
  right: 24rpx;
}

.fix-item {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.3);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  border-radius: 50%;
  /* 半透明背景色 */
  backdrop-filter: blur(20px);
  /* 背景模糊效果 */
  -webkit-backdrop-filter: blur(10px);
}

.border-right-dashed {
  border-right: 1px dashed #e88992;
}

.active-coupon {
  border-radius: 24rpx 24rpx 0 0;
  width: 100%;

  background: linear-gradient(to bottom, #ee4e31, #ee8b6e);
  position: relative;

  .activity-nav {
    height: 36rpx;
    background: #fdf9e7;
    color: #bd2e1b;
    font-size: 24rpx;
    line-height: 36rpx;
    padding: 0 16rpx;
    border-radius: 24rpx 24rpx 24rpx 0;
    margin-left: 16rpx;
  }
}

.shadow-card {
  position: relative;
  border-radius: 24rpx;
  background: white;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.question-circle-tip {
  position: absolute;
  background: rgba(0, 0, 0, 0.6);
  white-space: nowrap;

  top: -80rpx;
  left: -60rpx;
  padding: 12rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
  color: white;

  &::before {
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    border-left: 12rpx solid transparent;
    border-right: 12rpx solid transparent;
    border-top: 12rpx solid rgba(0, 0, 0, 0.6);
    bottom: -12rpx;
    left: 60rpx;
  }
}

.top--12 {
  top: -12rpx;
}

.page-footer {
  background: white;
  position: fixed;
  bottom: 0;
  left: 0;
}
</style>
